<template>
  <div class="templates-page">
    <!-- 顶部导航 -->
    <van-nav-bar title="维权模板库" fixed>
      <template #right>
        <van-icon name="search" size="18" @click="showSearch = true" />
      </template>
    </van-nav-bar>

    <!-- 搜索栏 -->
    <van-search
      v-show="showSearch"
      v-model="searchKeyword"
      placeholder="搜索模板"
      @search="onSearch"
      @cancel="showSearch = false"
      show-action
    />

    <!-- 分类导航 -->
    <div class="category-tabs">
      <van-tabs v-model:active="activeCategory" @change="onCategoryChange" sticky>
        <van-tab title="全部" name="all"></van-tab>
        <van-tab title="职场纠纷" name="workplace"></van-tab>
        <van-tab title="消费维权" name="consumer"></van-tab>
        <van-tab title="租房矛盾" name="housing"></van-tab>
        <van-tab title="其他" name="other"></van-tab>
      </van-tabs>
    </div>

    <!-- 热门推荐 -->
    <div v-if="activeCategory === 'all'" class="hot-section">
      <div class="section-header">
        <div class="section-title">🔥 热门模板</div>
        <div class="section-more" @click="viewMore('hot')">更多</div>
      </div>
      <div class="hot-templates">
        <div
          v-for="template in hotTemplates"
          :key="template.id"
          class="hot-template-card"
          @click="goToTemplate(template)"
        >
          <div class="template-icon">{{ template.icon }}</div>
          <div class="template-info">
            <div class="template-name">{{ template.name }}</div>
            <div class="template-usage">{{ template.usageCount }}人使用</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 模板列表 -->
    <div class="templates-list">
      <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
        <van-list
          v-model:loading="loading"
          :finished="finished"
          finished-text="没有更多了"
          @load="onLoad"
        >
          <div
            v-for="template in templateList"
            :key="template.id"
            class="template-item"
            @click="goToTemplate(template)"
          >
            <div class="template-header">
              <div class="template-category">{{ template.category }}</div>
              <div class="template-actions">
                <van-icon
                  :name="template.isCollected ? 'star' : 'star-o'"
                  :color="template.isCollected ? '#ff976a' : '#c8c9cc'"
                  @click.stop="toggleCollect(template)"
                />
              </div>
            </div>
            
            <div class="template-content">
              <div class="template-title">{{ template.name }}</div>
              <div class="template-desc">{{ template.description }}</div>
              
              <!-- 证据清单预览 -->
              <div v-if="template.evidenceList && template.evidenceList.length > 0" class="evidence-preview">
                <div class="evidence-title">需要准备的材料：</div>
                <div class="evidence-tags">
                  <span
                    v-for="evidence in template.evidenceList.slice(0, 3)"
                    :key="evidence"
                    class="evidence-tag"
                  >
                    {{ evidence }}
                  </span>
                  <span v-if="template.evidenceList.length > 3" class="evidence-more">
                    +{{ template.evidenceList.length - 3 }}
                  </span>
                </div>
              </div>
            </div>

            <div class="template-footer">
              <div class="template-stats">
                <span class="stat-item">
                  <van-icon name="eye-o" />
                  {{ template.usageCount }}次使用
                </span>
                <span class="stat-item">
                  <van-icon name="star-o" />
                  {{ template.collectCount }}收藏
                </span>
              </div>
              <div class="template-difficulty">
                <span class="difficulty-label">难度：</span>
                <van-rate
                  v-model="template.difficulty"
                  size="12"
                  color="#ff976a"
                  void-color="#eee"
                  readonly
                />
              </div>
            </div>
          </div>
        </van-list>
      </van-pull-refresh>
    </div>

    <!-- 底部导航 -->
    <van-tabbar v-model="activeTab" @change="onTabChange">
      <van-tabbar-item icon="home-o" to="/home">首页</van-tabbar-item>
      <van-tabbar-item icon="chat-o" to="/community">社区</van-tabbar-item>
      <van-tabbar-item icon="orders-o" to="/templates">工具</van-tabbar-item>
      <van-tabbar-item icon="user-o" to="/profile">我的</van-tabbar-item>
    </van-tabbar>

    <!-- 模板详情弹窗 -->
    <van-popup
      v-model:show="showTemplateDetail"
      position="bottom"
      :style="{ height: '80%' }"
      round
      closeable
    >
      <div v-if="selectedTemplate" class="template-detail">
        <div class="detail-header">
          <div class="detail-title">{{ selectedTemplate.name }}</div>
          <div class="detail-category">{{ selectedTemplate.category }}</div>
        </div>

        <div class="detail-content">
          <!-- 模板描述 -->
          <div class="detail-section">
            <div class="section-title">模板说明</div>
            <div class="section-content">{{ selectedTemplate.description }}</div>
          </div>

          <!-- 填写指南 -->
          <div v-if="selectedTemplate.fillGuide" class="detail-section">
            <div class="section-title">填写指南</div>
            <div class="section-content">{{ selectedTemplate.fillGuide }}</div>
          </div>

          <!-- 证据清单 -->
          <div v-if="selectedTemplate.evidenceList && selectedTemplate.evidenceList.length > 0" class="detail-section">
            <div class="section-title">必备证据材料</div>
            <div class="evidence-list">
              <div
                v-for="(evidence, index) in selectedTemplate.evidenceList"
                :key="index"
                class="evidence-item"
              >
                <van-icon name="checked" color="#52c41a" />
                <span>{{ evidence }}</span>
              </div>
            </div>
          </div>

          <!-- 模板预览 -->
          <div class="detail-section">
            <div class="section-title">模板预览</div>
          <div class="template-preview">
            {{ selectedTemplate.content ? selectedTemplate.content.substring(0, 200) + '...' : '暂无预览内容' }}
          </div>
          </div>

          <!-- 使用统计 -->
          <div class="detail-section">
            <div class="section-title">使用统计</div>
            <div class="usage-stats">
              <div class="stat-card">
                <div class="stat-number">{{ selectedTemplate.usageCount }}</div>
                <div class="stat-label">使用次数</div>
              </div>
              <div class="stat-card">
                <div class="stat-number">{{ selectedTemplate.collectCount }}</div>
                <div class="stat-label">收藏次数</div>
              </div>
              <div class="stat-card">
                <div class="stat-number">{{ selectedTemplate.successRate }}%</div>
                <div class="stat-label">成功率</div>
              </div>
            </div>
          </div>
        </div>

        <div class="detail-actions">
          <van-button
            :icon="selectedTemplate.isCollected ? 'star' : 'star-o'"
            @click="toggleCollect(selectedTemplate)"
          >
            {{ selectedTemplate.isCollected ? '已收藏' : '收藏' }}
          </van-button>
          <van-button type="primary" @click="useTemplate(selectedTemplate)">
            立即使用
          </van-button>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { showToast } from 'vant'
import { useUserStore } from '@/stores/user'
import { getTemplateList, collectTemplate } from '@/api/template'

const router = useRouter()
const userStore = useUserStore()

// 响应式数据
const activeCategory = ref('all')
const activeTab = ref(2)
const showSearch = ref(false)
const searchKeyword = ref('')
const refreshing = ref(false)
const loading = ref(false)
const finished = ref(false)
const showTemplateDetail = ref(false)
const selectedTemplate = ref(null)

// 模板列表
const templateList = ref([])
const hotTemplates = ref([])

// 模拟数据
const mockTemplates = [
  {
    id: 1,
    name: '劳动仲裁申请书',
    category: '职场纠纷',
    subCategory: '欠薪问题',
    description: '用于申请劳动仲裁的标准模板，适用于工资拖欠、违法解除劳动合同等情况',
    content: `劳动仲裁申请书

申请人：[姓名]，性别：[性别]，年龄：[年龄]岁
住址：[住址]
联系电话：[电话]

被申请人：[公司全称]
住所地：[公司地址]
法定代表人：[法人姓名]
联系电话：[公司电话]

仲裁请求：
1. 请求被申请人支付申请人工资[拖欠金额]元；
2. 请求被申请人支付申请人经济补偿金[补偿金额]元；
3. 本案仲裁费用由被申请人承担。

事实和理由：
[详细描述劳动关系、工作内容、拖欠工资情况等]

此致
[所在地]劳动人事争议仲裁委员会

申请人：[签名]
[申请日期]`,
    fillGuide: '请按照[]内的提示填写相应信息。公司全称可通过企查查等平台查询确认。拖欠金额需要有明确的计算依据。',
    evidenceList: ['劳动合同', '工资流水', '考勤记录', '工作证明', '身份证复印件'],
    usageCount: 1234,
    collectCount: 456,
    difficulty: 3,
    successRate: 85,
    isCollected: false,
    icon: '📄'
  },
  {
    id: 2,
    name: '消费者投诉函',
    category: '消费维权',
    subCategory: '产品质量',
    description: '向商家或相关部门投诉的标准模板，适用于产品质量问题、服务纠纷等',
    content: `消费者投诉函

致：[商家名称/相关部门]

投诉人：[姓名]
联系电话：[电话]
联系地址：[地址]

被投诉方：[商家名称]
地址：[商家地址]

投诉事由：
本人于[购买日期]在贵方购买[商品名称]，金额[购买金额]元。现发现该商品存在以下问题：
[详细描述问题]

诉求：
1. [具体要求，如退款、换货、赔偿等]
2. 承担相应法律责任

根据《消费者权益保护法》相关规定，请贵方在收到本函后[时限]内给予答复并妥善处理。

此致
敬礼！

投诉人：[签名]
[投诉日期]`,
    fillGuide: '填写时请保留购买凭证，详细描述问题和损失。时限一般为7-15个工作日。',
    evidenceList: ['购买凭证', '商品照片', '聊天记录', '检测报告'],
    usageCount: 856,
    collectCount: 234,
    difficulty: 2,
    successRate: 92,
    isCollected: true,
    icon: '🛒'
  },
  {
    id: 3,
    name: '租房押金退还申请书',
    category: '租房矛盾',
    subCategory: '押金纠纷',
    description: '用于向房东申请退还押金的正式文书，包含法律依据和具体要求',
    content: `租房押金退还申请书

致：[房东姓名/房屋中介]

申请人：[姓名]
联系电话：[电话]
身份证号：[身份证号]

房屋地址：[租赁房屋地址]
租赁期间：[起始日期]至[结束日期]
押金金额：[押金数额]元

申请事由：
本人已于[搬离日期]正式搬离上述租赁房屋，租赁期满。根据租赁合同约定和相关法律规定，现申请退还租房押金。

房屋现状：
经双方验收，房屋及设施设备状况良好，无人为损坏，符合退还押金条件。

法律依据：
根据《民法典》相关规定，租赁期满承租人返还租赁物的，出租人应当返还押金。

特此申请，请于收到本申请书后[时限]内将押金[金额]元退还至本人账户。

申请人：[签名]
[申请日期]`,
    fillGuide: '搬离前建议拍照记录房屋状况，保留交接清单。如有争议可申请第三方评估。',
    evidenceList: ['租赁合同', '押金收据', '房屋交接清单', '房屋现状照片'],
    usageCount: 642,
    collectCount: 189,
    difficulty: 2,
    successRate: 78,
    isCollected: false,
    icon: '🏠'
  },
  {
    id: 4,
    name: '网购退货申请书',
    category: '消费维权',
    subCategory: '退款退货',
    description: '网络购物七天无理由退货或质量问题退货的申请模板',
    content: `网购退货申请书

致：[商家名称]

申请人：[姓名]
联系电话：[电话]
订单号：[订单编号]

商品信息：
商品名称：[商品名称]
购买时间：[下单时间]
商品价格：[商品价格]元

退货原因：
□ 七天无理由退货
□ 商品质量问题
□ 商品与描述不符
□ 其他：[具体说明]

详细说明：
[详细描述退货原因和商品问题]

退货要求：
1. 退还商品价款[金额]元
2. 退还运费[金额]元（如适用）
3. 处理时限：[期望处理时间]

根据《消费者权益保护法》和《网络购买商品七日无理由退货暂行办法》相关规定，请贵方及时处理本次退货申请。

申请人：[签名]
[申请日期]`,
    fillGuide: '七天无理由退货需在签收后7天内申请，商品需保持原状。质量问题退货不受时间限制。',
    evidenceList: ['订单截图', '商品照片', '聊天记录', '快递单号'],
    usageCount: 423,
    collectCount: 156,
    difficulty: 1,
    successRate: 95,
    isCollected: false,
    icon: '📦'
  }
]

// 热门模板数据
const mockHotTemplates = [
  { id: 1, name: '劳动仲裁申请书', icon: '📄', usageCount: 1234 },
  { id: 2, name: '消费者投诉函', icon: '🛒', usageCount: 856 },
  { id: 3, name: '押金退还申请', icon: '🏠', usageCount: 642 },
  { id: 4, name: '网购退货申请', icon: '📦', usageCount: 423 }
]

// 方法
const onCategoryChange = (name) => {
  activeCategory.value = name
  refreshTemplateList()
}

const onRefresh = () => {
  refreshing.value = true
  templateList.value = []
  finished.value = false
  loadTemplates().finally(() => {
    refreshing.value = false
  })
}

const onLoad = () => {
  loadTemplates()
}

const loadTemplates = async () => {
  loading.value = true
  
  try {
    const params = {
      page: Math.floor(templateList.value.length / 10) + 1,
      size: 10,
      category: activeCategory.value === 'all' ? null : activeCategory.value,
      keyword: searchKeyword.value || null
    }
    
    const response = await getTemplateList(params)
    const newTemplates = response.data.records || response.data || []
    
    if (newTemplates.length === 0) {
      finished.value = true
    } else {
      templateList.value.push(...newTemplates)
    }
  } catch (error) {
    console.error('加载模板失败:', error)
    // 使用模拟数据作为后备
    const startIndex = templateList.value.length
    const pageSize = 10
    let filteredTemplates = mockTemplates
    
    // 根据分类筛选
    if (activeCategory.value !== 'all') {
      const categoryMap = {
        workplace: '职场纠纷',
        consumer: '消费维权',
        housing: '租房矛盾',
        other: '其他'
      }
      filteredTemplates = mockTemplates.filter(t => 
        t.category === categoryMap[activeCategory.value]
      )
    }
    
    // 搜索筛选
    if (searchKeyword.value) {
      filteredTemplates = filteredTemplates.filter(t =>
        t.name.includes(searchKeyword.value) ||
        t.description.includes(searchKeyword.value)
      )
    }
    
    const newTemplates = filteredTemplates.slice(startIndex, startIndex + pageSize)
    
    if (newTemplates.length === 0) {
      finished.value = true
    } else {
      templateList.value.push(...newTemplates)
    }
  } finally {
    loading.value = false
  }
}

const refreshTemplateList = () => {
  templateList.value = []
  finished.value = false
  loadTemplates()
}

const onSearch = () => {
  refreshTemplateList()
}

const goToTemplate = (template) => {
  selectedTemplate.value = template
  showTemplateDetail.value = true
}

const useTemplate = (template) => {
  if (!userStore.isLoggedIn) {
    showToast('请先登录')
    router.push('/login')
    return
  }
  
  // 跳转到模板填写页面
  router.push(`/templates/fill/${template.id}`)
  showTemplateDetail.value = false
}

const toggleCollect = async (template) => {
  if (!userStore.isLoggedIn) {
    showToast('请先登录')
    return
  }
  
  try {
    await collectTemplate(template.id)
    template.isCollected = !template.isCollected
    template.collectCount += template.isCollected ? 1 : -1
    showToast(template.isCollected ? '收藏成功' : '取消收藏')
  } catch (error) {
    console.error('收藏操作失败:', error)
    showToast('操作失败')
  }
}

const viewMore = (type) => {
  if (type === 'hot') {
    // 查看更多热门模板
    showToast('查看更多热门模板')
  }
}

const onTabChange = (index) => {
  activeTab.value = index
}

onMounted(() => {
  hotTemplates.value = mockHotTemplates
  loadTemplates()
})
</script>

<style scoped>
.templates-page {
  min-height: 100vh;
  background: #f7f8fa;
  padding-bottom: 50px;
}

.category-tabs {
  background: white;
  position: sticky;
  top: 46px;
  z-index: 99;
}

.hot-section {
  background: white;
  margin-bottom: 8px;
  padding: 16px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #323233;
}

.section-more {
  font-size: 14px;
  color: #1989fa;
  cursor: pointer;
}

.hot-templates {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
}

.hot-template-card {
  background: #f7f8fa;
  border-radius: 8px;
  padding: 16px;
  display: flex;
  align-items: center;
  gap: 12px;
  cursor: pointer;
  transition: all 0.2s;
}

.hot-template-card:hover {
  background: #e8f2ff;
}

.template-icon {
  font-size: 24px;
}

.template-info {
  flex: 1;
}

.template-name {
  font-size: 14px;
  font-weight: 600;
  color: #323233;
  margin-bottom: 4px;
}

.template-usage {
  font-size: 12px;
  color: #969799;
}

.templates-list {
  padding: 8px 0;
}

.template-item {
  background: white;
  margin-bottom: 8px;
  padding: 16px;
  cursor: pointer;
}

.template-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.template-category {
  font-size: 12px;
  padding: 2px 8px;
  background: #f0f9ff;
  color: #1989fa;
  border-radius: 4px;
}

.template-content {
  margin-bottom: 16px;
}

.template-title {
  font-size: 16px;
  font-weight: 600;
  color: #323233;
  margin-bottom: 8px;
}

.template-desc {
  font-size: 14px;
  color: #646566;
  line-height: 1.5;
  margin-bottom: 12px;
}

.evidence-preview {
  background: #f7f8fa;
  border-radius: 6px;
  padding: 12px;
}

.evidence-title {
  font-size: 12px;
  color: #646566;
  margin-bottom: 8px;
}

.evidence-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
}

.evidence-tag {
  font-size: 11px;
  padding: 2px 6px;
  background: white;
  color: #323233;
  border-radius: 3px;
  border: 1px solid #eee;
}

.evidence-more {
  font-size: 11px;
  padding: 2px 6px;
  background: #1989fa;
  color: white;
  border-radius: 3px;
}

.template-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 12px;
  border-top: 1px solid #f0f0f0;
}

.template-stats {
  display: flex;
  gap: 16px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: #969799;
}

.template-difficulty {
  display: flex;
  align-items: center;
  gap: 4px;
}

.difficulty-label {
  font-size: 12px;
  color: #646566;
}

.template-detail {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.detail-header {
  padding: 20px 16px;
  border-bottom: 1px solid #eee;
}

.detail-title {
  font-size: 18px;
  font-weight: 600;
  color: #323233;
  margin-bottom: 8px;
}

.detail-category {
  font-size: 14px;
  color: #1989fa;
}

.detail-content {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
}

.detail-section {
  margin-bottom: 24px;
}

.detail-section .section-title {
  font-size: 16px;
  font-weight: 600;
  color: #323233;
  margin-bottom: 12px;
}

.section-content {
  font-size: 14px;
  color: #646566;
  line-height: 1.6;
}

.evidence-list {
  space-y: 8px;
}

.evidence-item {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  color: #323233;
  margin-bottom: 8px;
}

.template-preview {
  background: #f7f8fa;
  border-radius: 8px;
  padding: 16px;
  font-size: 13px;
  color: #646566;
  line-height: 1.6;
  font-family: monospace;
  white-space: pre-line;
}

.usage-stats {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 12px;
}

.stat-card {
  text-align: center;
  background: #f7f8fa;
  border-radius: 8px;
  padding: 16px;
}

.stat-number {
  font-size: 20px;
  font-weight: 600;
  color: #1989fa;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 12px;
  color: #646566;
}

.detail-actions {
  padding: 16px;
  border-top: 1px solid #eee;
  display: flex;
  gap: 12px;
}

.detail-actions .van-button {
  flex: 1;
}
</style>